var fs = require('fs')
  , async = require('async')
  , probe = require('node-ffprobe')
  , path = require('path')
  , config = require('../config')
  , Synchronizer = require('./Synchronizer');

//json变为image的方法
var J2I = {
	/**
	 * 转换为图片
	 * @param callback 转换完成的回调
	 */
	convert : function(callback){
		async.waterfall([
			//1.得到音频
			function(cb){
				var rsPath = config.originPath;
				if(fs.existsSync(path.join(rsPath, 'audio'))){
					rsPath = path.join(rsPath, 'audio');
				}
				if(fs.existsSync(path.join(rsPath, 'audio.aac'))){
					cb(null,path.join(rsPath, 'audio.aac'));
				}else if(fs.existsSync(path.join(rsPath, 'audio.mp3'))){
					cb(null,path.join(rsPath, 'audio.mp3'));
				}else if(fs.existsSync(path.join(rsPath, 'audio.ogg'))){
					cb(null,path.join(rsPath, 'audio.ogg'));
				}else if(fs.existsSync(path.join(rsPath, 'audio.caf'))){
                    cb(null,path.join(rsPath, 'audio.caf'));
                }else{
					cb(new Error("音频文件没有找到"));
				}
			},
			//2.得到音频时长
			function(audioPath,cb){
				probe(audioPath, function(err, probeData) {
					if(typeof probeData === "undefined"){
						cb(new Error("error:audio,content:解析音频时出错,请检查音频文件"));
					}else{
						//console.log(probeData);
						cb(err,probeData.streams[0].duration);
					}
				});
			},
			//3.通过同步器转换为图片
			function(duration,cb){
				console.log("音频时常%s",duration);
				var sync = new Synchronizer(duration);
				sync.convert(function(err){
					cb();
				});
			}
		],function(err){
			callback(err);
		});
	}
};

module.exports = J2I;